package com.bianguo.android.hotfixlibrary;

import android.content.Context;

import com.bianguo.android.hotfixlibrary.utils.Constants;

import java.io.File;
import java.util.HashSet;

import dalvik.system.DexClassLoader;
import dalvik.system.PathClassLoader;

public class FixDexManager {

    private static volatile FixDexManager instance;
    private HashSet<File> loadedDex;

    private FixDexManager() {
        loadedDex = new HashSet<>();
    }

    public static FixDexManager getInstance() {
        FixDexManager manager = instance;
        if (manager == null) {
            synchronized (FixDexManager.class) {
                if (manager == null) {
                    manager = new FixDexManager();
                    instance = manager;
                }
            }
        }
        return manager;
    }

    public void loadFixedDex(Context mContext) {
        if (mContext == null) {
            return;
        }
        File fileDir = mContext.getDir(Constants.DEX_DIR, Context.MODE_PRIVATE);
        File[] files = fileDir.listFiles();
        for (File file : files) {
            String name = file.getName();
            if (name.endsWith(Constants.DEX_SUFFIX) && !"classes.dex".equals(name)) {
                loadedDex.add(file);
            }
        }

        createDexClassLoader(mContext, fileDir);
    }

    private void createDexClassLoader(Context mContext, File fileDir) {
        String optimizedDir = fileDir.getAbsolutePath() + File.separator + "opt_dex";
        File fopt = new File(optimizedDir);
        if (!fopt.exists()) {
            fopt.mkdirs();
        }
        for (File dex : loadedDex) {
            DexClassLoader classLoader = new DexClassLoader(dex.getAbsolutePath(), optimizedDir,
                    null, mContext.getClassLoader());
            hotfix(mContext, classLoader);
        }
    }

    private void hotfix(Context mContext, DexClassLoader classLoader) {
        PathClassLoader pathLoader = (PathClassLoader) mContext.getClassLoader();
    }
}
